package com.pqc.tbk.utils;

import java.security.MessageDigest;

/**
 * 加密工具类
 * 
 * @author Ping_QC created on 2012-7-3 上午10:48:07
 * 
 */
public class Digest {

	private static final String MD5 = "MD5";
	private static final String SHA1 = "SHA-1";
	private static final String APPSECRET = "";

	private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5",
			"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

	/**
	 * 转换字节数组为16进制字串
	 * 
	 * @param b
	 *            字节数组
	 * @return 16进制字串
	 */

	private static String byteArrayToHexString(final byte[] b) {
		final StringBuffer resultSb = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			resultSb.append(byteToHexString(b[i]));
		}
		return resultSb.toString();
	}

	private static String byteToHexString(final byte b) {
		int n = b;
		if (n < 0) {
			n = 256 + n;
		}
		final int d1 = n / 16;
		final int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}

	public static String md5(final String origin) {
		return encode(origin, "", MD5);
	}

	public static String sha1(final String origin) {
		return encode(origin, "", SHA1);
	}

	public static String md5(final String origin, String secret) {
		if (StringUtil.isEmptyOrNull(secret)) {
			secret = APPSECRET;
		}
		return encode(origin, secret, MD5);
	}

	public static String sha1(final String origin, String secret) {
		if (StringUtil.isEmptyOrNull(secret)) {
			secret = APPSECRET;
		}
		return encode(origin, secret, SHA1);
	}

	private static String encode(final String origin, final String secret,
			final String algorithm) {

		String resultString = null;

		try {
			resultString = new String(origin + secret);
			final MessageDigest md = MessageDigest.getInstance(algorithm);
			resultString = byteArrayToHexString(md.digest(resultString
					.getBytes()));
		} catch (final Exception ex) {

		}
		return resultString;
	}
}
